package 其他;

/**
 * @author ssh
 * @date 2025/9/14
 * @description
 */
public class 多个线程循环打印abc {
    private static final Object lock = new Object();
    private static int state = 0; // 0:A, 1:B, 2:C

    public static void main(String[] args) {
        new Thread(() -> print("A", 0)).start();
        new Thread(() -> print("B", 1)).start();
        new Thread(() -> print("C", 2)).start();
    }

    private static void print(String name, int targetState) {
        for (int i = 0; i < 10; i++) {
            synchronized (lock) {
                while (state % 3 != targetState) {
                    try {
                        lock.wait(); // 当前线程等待
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(name);
                state++;
                lock.notifyAll(); // 唤醒其他线程
            }
        }
    }

}
